package cn.jdy.payment.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.BankConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.IpUtil;
import cn.jdy.payment.entity.OrderParameter;
import cn.jdy.payment.entity.Orders;
import cn.jdy.payment.service.OnlinePayHandler;
import cn.jdy.payment.service.OrderService;
import cn.jdy.plugins.entity.Business;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.BusinessService;

/**
 * Created by Tianyi on 2014/5/31.
 */
@Controller
@RequestMapping("/olpGW")
public class OnlinePayCtrl extends BaseCtrl {

	@Autowired
	private BusinessService businessService;
	@Autowired
	private OrderService orderService;

	/**
	 * 判断是否符合购买条件
	 * @param businessId
	 * @return
	 */
	@RequestMapping("/check/{businessId}")
	@ResponseBody
	public Map<String, Object> check(@PathVariable String businessId) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			Member member = getMember(true);
			if(member != null) {
				Business business = businessService.queryById(businessId);
				if(business != null) {
					//判断此商机是否是当前用户提供的，如果是当前用户提供
					if(member.getId().equals(business.getCreater())) {
						jsonMap.put("statusCode", 201);
						jsonMap.put("msg", "此商机是您上传的，不需要购买！");
					} else {
						//判断此商机的库存是否大于0
						if(business.getStock() != null && business.getStock() > 0) {
							//判断用户是否下载过此商机信息
							if(!orderService.queryHasOrder(member.getId(), businessId, new String[]{BankConstant.ORDER_SUC, BankConstant.ORDER_UNPAY}))
								if("0".equals(member.getUserType()) && member.getMoney() < business.getPrice()) {
									jsonMap.put("statusCode", 400);
									jsonMap.put("msg", "对不起，您的S币不足！");
								}else
									jsonMap.put("statusCode", 200);
							else {
								jsonMap.put("statusCode", 202);
								jsonMap.put("msg", "您已经购买过此商机，是否跳到“我的订单”查看？");
							}
						} else {
							jsonMap.put("statusCode", 400);
							jsonMap.put("msg", "对不起，此商机库存不足！");
						}
					}
				} else {
					throw new RuntimeException("查询商机失败：" + businessId);
				}
			} else {
				jsonMap.put("statusCode", 500);
				jsonMap.put("msg", "请登录后下载！");
			}
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			jsonMap.put("msg", "对不起，此商机暂时不能下载！");
			BaseLog.e(this.getClass(), "查询错误", e);
		}
		return jsonMap;
	}

	/**
	 * 准备订单
	 */
	@RequestMapping("/readyOrder/{type}")
	public ModelAndView readyOrder(@PathVariable String type, @RequestParam(required = false) String businessid) {
		ModelAndView mv = new ModelAndView("0".equals(getMember(false).getUserType()) ? "/payment/payment_Person.jsp" : "/payment/payment.jsp");
		mv.addObject("balance", getMember(true).getMoney());
		mv.addObject("exchange", BankConstant.EXCHANGE);
		if("topUp".equals(type)) {
			mv.addObject("action", "/olpGW/topUpOrder");
			mv.addObject("type", 1);
		}else {
			mv.addObject("businessid", businessid);
			mv.addObject("price", businessService.queryById(businessid).getPrice());
			mv.addObject("action", "/olpGW/sureOrder");
			mv.addObject("type", 0);
		}
		return mv;
	}

	/**
	 * 生成订单
	 *
	 * @return
	 */
	@RequestMapping("/sureOrder")
	public ModelAndView sureOrder(@RequestParam String businessid, @RequestParam(required = false) boolean useBalance, @RequestParam(required = false) String bankNo) {
		ModelAndView mv = new ModelAndView();
		Member member = getMember(true);
		Business businessEntity = businessService.queryById(businessid);
		int price = businessEntity.getPrice();//商机价格
		int balance = member.getMoney();//账户余额
		int sMoney = 0;//使用S币数量
		double money = 0;//需要支付的金额
		if(useBalance) {
			sMoney = price > balance ? balance : price;
			money = price > sMoney ? ((price - sMoney) * BankConstant.EXCHANGE) : 0;
		} else {
			money = price * BankConstant.EXCHANGE;
		}
		OrderParameter param = new OrderParameter();
		param.setBankNo(bankNo);
		param.setsMoney(sMoney);
		param.setMoney(money);
		param.setOperIp(IpUtil.getIp(request));
		param.setPayType("0");//0:PC, 1:App
		param.setOrderType(BankConstant.ORDER_TYPE_PAY);//1:支付, 2:退款
		param.setGoodNo(businessid);
		param.setGoodSum("1");
		param.setUserId(member.getId());
		param.setUserName(member.getUserName());
		try {
			Orders order = orderService.createOrder(param);
			if(order != null) {
				businessEntity.setStock(businessEntity.getStock() - 1);//减少库存
				businessService.update(businessEntity);
				member.setMoney(balance - sMoney);//扣除S币
				memberService.update(member);
				session.setAttribute("user", member);
				if(money > 0) {
					orderService.addScheduler(order.getId());
					mv.addObject("order", order);
					mv.setViewName("/payment/orderSubmit.jsp");
				} else {
					order.setStatus(BankConstant.ORDER_SUC);
					if(BankConstant.BACK_BUSI_HANDLE_SUC.equals(orderService.bankNotifyHandle(order))) {
						mv.addObject("statusCode", 200);
						mv.addObject("message", "恭喜，购买成功！");
						mv.addObject("amounts", order.getAmount());
					} else {
						mv.addObject("statusCode", 500);
						mv.addObject("message", "对不起，付款遇到问题，请联系客服人员解决！");
					}
					mv.setViewName("/payment/payResult.jsp");
				}
			} else {
				throw new RuntimeException();
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "sureOrder生成订单异常！", e);
		}
		return mv;
	}

	/**
	 * 生成订单(充值)
	 *
	 * @return
	 */
	@RequestMapping("/topUpOrder")
	public ModelAndView topUpOrder(@RequestParam int sMoney, @RequestParam String bankNo) {
		ModelAndView mv = new ModelAndView();
		OrderParameter param = new OrderParameter();
		param.setBankNo(bankNo);
		param.setsMoney(sMoney);
		param.setMoney(sMoney * BankConstant.EXCHANGE);
		param.setOperIp(IpUtil.getIp(request));
		param.setPayType("0");//0:PC, 1:App
		param.setOrderType(BankConstant.ORDER_TYPE_TOPUP);//1:支付, 2:退款
		param.setGoodSum("1");
		Member member = getMember(false);
		param.setUserId(member.getId());
		param.setUserName(member.getUserName());
		try {
			Orders order = orderService.createOrder(param);
			if(order != null) {
				orderService.addScheduler(order.getId());
				mv.setViewName("/payment/orderSubmit.jsp");
				mv.addObject("order", order);
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "sureOrder生成订单异常！", e);
		}
		return mv;
	}

	/**
	 * 继续付款
	 */
	@RequestMapping("/pay/{orderNo}")
	public ModelAndView pay(@PathVariable String orderNo, @RequestParam(required = false) String bankNo) {
		ModelAndView mv = new ModelAndView();
		try {
			Orders order = orderService.queryOrderById(orderNo);
			if(order != null) {
				if(bankNo != null && !bankNo.isEmpty()) {
					order.setBankNo(bankNo);
					orderService.update(order);
				}
				order = orderService.createOrderBankData(order);
				mv.setViewName("/payment/orderSubmit.jsp");
				mv.addObject("order", order);
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "sureOrder生成订单异常！", e);
		}
		return mv;
	}

	/**
	 * 银行回调
	 *
	 * @param bankType
	 * @return
	 */
	@RequestMapping("/notify/{bankType}")
	public ModelAndView notify(@PathVariable("bankType") String bankType) {
		return notify(bankType, null);
	}

	/**
	 * 银行回调（带银行版本信息）
	 *
	 * @param bankType
	 * @param version
	 * @return
	 */
	@RequestMapping("/notify/{bankType}/{version}")
	public ModelAndView notify(@PathVariable("bankType") String bankType, @PathVariable("version") String version) {
		ModelAndView mv = new ModelAndView("/payment/payResult.jsp");
		try {
			Map<String, String> param = OnlinePayHandler.getDataFromRequest(request, "upomp".equals(bankType));
			if(version != null) param.put("version", version);

			Orders order = orderService.notify(bankType, param);
			switch(Integer.parseInt(order.getStatus())) {
				case 1:
					mv.addObject("statusCode", 200);
					mv.addObject("message", "恭喜，付款成功！");
					mv.addObject("amounts", order.getAmount());
					orderService.deleteScheduler(order.getId());
					break;
				default:
					mv.addObject("statusCode", 500);
					mv.addObject("message", "对不起，付款遇到问题，请联系客服人员解决！");
					break;
			}
		} catch(Exception e) {
			mv.addObject("statusCode", 500);
			mv.addObject("message", "对不起，付款遇到问题，请联系客服人员解决！");
			BaseLog.e(getClass(), "银行回调异常：" + bankType, e);
		}
		return mv;
	}

	/**
	 * 准备订单(充值)
	 *
	 * @return
	 */
	@RequestMapping("/cancel/{orderNo}")
	@ResponseBody
	public boolean cancel(@PathVariable String orderNo) {
		try {
			return "3".equals(orderService.cancel(orderNo));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "cancel", e);
		}
		return false;
	}

}
